package admin

import (
	"encoding/json"
	"fmt"
	"time"

	"gitee.com/lflxp/dogo"
)

// 继承xorm.Engine 扩展InsertHistory自动插入History历史
func InsertHistory(beans ...interface{}) (int64, error) {
	defer func() {
		data, err := json.Marshal(beans)
		if err != nil {
			dogo.NewRails().Error(err)
			return
		}
		info := History{
			Name:   "FHST操作",
			Op:     fmt.Sprintf("添加 %s", string(data)),
			Common: "fhst op",
		}
		_, err = AddHistory(&info)
		if err != nil {
			dogo.NewRails().Error(err)
		}

	}()
	return dogo.NewRails().Orm.Insert(beans...)
}

type History struct {
	Id     int64     `xorm:"id pk not null autoincr" name:"id"`
	Name   string    `xorm:"name" name:"name" verbose_name:"操作历史" list:"true"`
	Op     string    `xorm:"op" name:"op" verbose_name:"操作"`
	Common string    `xorm:"common" name:"common" verbose_name:"备注"`
	Create time.Time `xorm:"created"` //这个Field将在Insert时自动赋值为当前时间
	Update time.Time `xorm:"updated"` //这个Field将在Insert或Update时自动赋值为当前时间
}

func getByUUIDHistory(uuid string) (*History, bool, error) {
	data := new(History)
	has, err := dogo.NewRails().Orm.Where("uuid = ?", uuid).Get(data)
	return data, has, err
}

func AddHistory(data *History) (int64, error) {
	affected, err := dogo.NewRails().Orm.Insert(data)
	return affected, err
}

func DelHistory(id string) (int64, error) {
	data := new(History)
	affected, err := dogo.NewRails().Orm.ID(id).Delete(data)
	return affected, err
}

func UpdateHistory(id string, data *History) (int64, error) {
	affected, err := dogo.NewRails().Orm.Table(new(History)).ID(id).Update(data)
	return affected, err
}
